package com.duofan.gmall.order.listener;

import com.duofan.gmall.order.config.MyRabbitMQConfig;
import com.duofan.gmall.order.entity.OrderEntity;
import com.duofan.gmall.order.service.OrderService;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Slf4j
@Component
@RabbitListener(queues = MyRabbitMQConfig.ORDER_RELEASE_ORDER_QUEUE)
public class OrderCloseListener {

    @Autowired
    OrderService orderService;

    @RabbitHandler
    public void handler(OrderEntity orderEntity, Channel channel, Message message) throws IOException {
        log.info("接受到消息, 准备关闭订单: {}", orderEntity.getOrderSn());
        try {
            // Boolean redelivered = message.getMessageProperties().getRedelivered();
            orderService.closeOrder(orderEntity);
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        } catch (Exception e) {
            channel.basicReject(message.getMessageProperties().getDeliveryTag(), true);
        }
    }

}
